package com.contacts.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.contacts.pojo.Contact;
import com.contacts.utils.DataSourceUtils;

public class ContactDao {
	//查找所有
	public List<Contact> findAllContact() throws SQLException {
		String sql = "select * from contact";
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		return runner.query(sql, new BeanListHandler<Contact>(Contact.class));
	}
	public int addContactDao(Contact contact) throws SQLException {
		String sql = "insert into contact values(?,?,?,?,?)";
		QueryRunner runner=new QueryRunner(DataSourceUtils.getDataSource());
		return runner.update(sql,null,contact.getName(),contact.getPhone(),contact.getAddr(),contact.getRem());
	}
	public Contact findContactByIdDao(String id) throws SQLException {
		String sql = "select * from contact where id=?";
		QueryRunner runner=new QueryRunner(DataSourceUtils.getDataSource());
		return runner.query(sql, new BeanHandler<Contact>(Contact.class),id);
	}
	public int updateContactDao(Contact contact) throws SQLException {
		String sql = "update contact set name=?,phone=?,addr=?,rem=? where id=?";
		QueryRunner runner=new QueryRunner(DataSourceUtils.getDataSource());
		return runner.update(sql,contact.getName(),contact.getPhone(),contact.getAddr(),contact.getRem(),contact.getId());
	}
	public int deleteContactByIdDao(String id) throws SQLException {
		String sql = "delete from contact where id=?";
		QueryRunner runner=new QueryRunner(DataSourceUtils.getDataSource());
		return runner.update(sql,id);
	}
}
